﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Utils;
using NP.BPMReportPlatform.YJJSZHSQ.Dtos;
using SqlSugar;
using Volo.Abp.Application.Dtos;

namespace NP.BPMReportPlatform.YJJSZHSQ
{

    public class YJJSZHSQService : BPMReportPlatformAppService, IYJJSZHSQService
    {
        private readonly SqlSugarClient _db;
        private readonly SqlSugarClient _dbPlatform;
        private readonly IBPMUtilsAppService _bPmUtilsApp;
        private readonly IBPMPlatformAppService _iBpmPlatformApp;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        /// <param name="bPmUtilsApp"></param>
        /// <param name="iBpmPlatformApp"></param>
        public YJJSZHSQService(ISqlSugarAppService sqlSugarAppService, IBPMUtilsAppService bPmUtilsApp, IBPMPlatformAppService iBpmPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPmUtilsApp = bPmUtilsApp;
            _iBpmPlatformApp = iBpmPlatformApp;
        }


        public async Task<PagedResultDto<GetYJJSZHSQOutput>> GetAllAsync(GetYJJSZHSQInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBpmPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPmUtilsApp.GetProcessUrl(x.InstanceNumber, userId));

            //返回结果
            return new PagedResultDto<GetYJJSZHSQOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        public async Task<List<GetYJJSZHSQOutput>> ExportAsync(GetYJJSZHSQInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            return listViewDto;
        }


        private ISugarQueryable<GetYJJSZHSQOutput> GetQueryable(GetYJJSZHSQInput input)
        {
            var currentUserId = Guid.Empty;
            if (!input.IsQueryAll && CurrentUser != null)
            {
                var currentUserDto = _dbPlatform.Queryable<Users>()
                    .Where(x => x.WorkNumber.Equals(CurrentUser.UserName)).First();
                if (currentUserDto != null)
                {
                    currentUserId = currentUserDto.UserId;
                }
            }

            var listQueryable = _db.Queryable<YJJSZHSQDetail, YJJSZHSQHeader, BusinessProcessesNew>(
                    (a, b, c) => new JoinQueryInfos(JoinType.Left, a.InstanceNumber == b.InstanceNumber, JoinType.Left, b.InstanceNumber == c.InstanceId)
                )
                .WhereIF(!input.IsQueryAll, (a, b, c) => b.AddUserId.Equals(currentUserId))
                .WhereIF(!string.IsNullOrWhiteSpace(input.InstanceNumber),
                    (a, b, c) => b.InstanceNumber == input.InstanceNumber)
                .WhereIF(!input.OrderStatus.IsNullOrEmpty(),
                    (a, b, c) => SqlFunc.ContainsArray(input.OrderStatus.ToArray(), c.ProcessStatusCode))
                .WhereIF(!string.IsNullOrWhiteSpace(input.AddUserName),
                    (a, b, c) => b.AddUserName.Contains(input.AddUserName))
                .WhereIF(input.StartCreationTime != null && input.EndCreationTime != null,
                    (a, b, c) => c.StartTime >= input.StartCreationTime && c.StartTime <= input.EndCreationTime)
                .WhereIF(!string.IsNullOrWhiteSpace(input.Title), (a, b, c) => b.Title.Contains(input.Title))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Content), (a, b, c) => b.Title.Contains(input.Content))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Name), (a, b, c) => a.Name.Contains(input.Name))
                .WhereIF(!string.IsNullOrWhiteSpace(input.Account), (a, b, c) => a.Account.Contains(input.Account))
                .WhereIF(!string.IsNullOrWhiteSpace(input.CompanyCode),
                    (a, b, c) => a.CompanyCode.Contains(input.CompanyCode))
                .Select((a, b, c) => new GetYJJSZHSQOutput()
                {
                    InstanceNumber = b.InstanceNumber,
                    ProcessStartTime = b.AddTime,
                    ProcessStartUserName = b.AddUserName,
                    OrderStatus = c.ProcessStatusName,

                    Content = b.Content,
                    Title = b.Title,
                    Account = a.Account,
                    CompanyCode = a.CompanyCode,
                    Name = a.Name

                }).MergeTable().Distinct().OrderBy(ins => ins.ProcessStartTime, OrderByType.Desc);
            // var sql = listQueryable.ToSql().Key;
            return listQueryable;
        }
    }
}